package cn.edu.scau.cmi.qiuzeyang.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.qiuzeyang.domain.Student;

public class StudentDao extends HibernateSessionImpl {

	public static final String NAME = "name";

	public void save(Student transientInstance) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.save(transientInstance);
		transaction.commit();
		session.close();
	}

	public void delete(Student persistentInstance) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(persistentInstance);
		transaction.commit();
		session.close();
	}

	public void update(Student student) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.update(student);
		transaction.commit();
		session.close();
	}

	public Student findById(Long id) {
		Session session = getSession();
		Student student = (Student) session.get("cn.edu.scau.cmi.qiuzeyang.hibernate.domain.Student", id);
		session.close();
		return student;
	}

	public List<Student> findByProperty(String propertyName, Object value) {
		Session session = getSession();
		String queryString = "select * from student where " + propertyName + " = ?";
		Query queryObject = session.createSQLQuery(queryString).addEntity(Student.class);
		queryObject.setParameter(0, value);
		List<Student> list = queryObject.list();
		session.close();
		return list;
	}

	public List<Student> findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List<Student> findAll() {
		Session session = getSession();
		String queryString = "select * from student";
		Query queryObject = session.createSQLQuery(queryString).addEntity(Student.class);
		List<Student> list = queryObject.list();
		session.close();
		return list;
	}

}
